﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kai.Me.HtmlText.Models.Repositories.Contracts;
using Kai.Me.HtmlText.Models.Data.Contracts;
using Kai.MvcEngine.Core.Components;
using Kai.Me.HtmlText.Models.Data.Entities;
using Kai.MvcEngine.Core.Configuration.Utils;

namespace Kai.Me.HtmlText.Models.Repositories
{
    public class HtmlTextRepository : IHtmlTextRepository
    {
        public IHtmlText GetByContainer(int ctrId)
        {
            using (MvcEngineDataContext context = new MvcEngineDataContext(ConfigurationUtil.ConnectionString))
            {
                return context.me_HtmlTexts.FirstOrDefault(h => h.PageContentId == ctrId);
            }
        }

        public void Save(IHtmlText item)
        {
            using (MvcEngineDataContext context = new MvcEngineDataContext(ConfigurationUtil.ConnectionString))
            {
                context.me_HtmlTexts.InsertOnSubmit((me_HtmlText)item);
                context.SubmitChanges();
            }
        }

        public IHtmlText Create()
        {
            return new me_HtmlText();
        }

        public void Update(IHtmlText item)
        {
            using (MvcEngineDataContext context = new MvcEngineDataContext(ConfigurationUtil.ConnectionString))
            {
                me_HtmlText updItem = context.me_HtmlTexts.Single(h => h.Id == item.Id);
                updItem.Text = item.Text;
                updItem.Modified = item.Modified;
                updItem.ModifiedBy = item.ModifiedBy;
                context.SubmitChanges();
            }
        }

        public void DeleteByPageContent(int pageContent)
        {
            using (MvcEngineDataContext context = new MvcEngineDataContext(ConfigurationUtil.ConnectionString))
            {
                 IHtmlText item = context.me_HtmlTexts.SingleOrDefault(h => h.PageContentId == pageContent);
                 if (item != null)
                 {
                     context.me_HtmlTexts.DeleteOnSubmit((me_HtmlText)item);
                     context.SubmitChanges();
                 }
            }
        }
    }
}
